#!/bin/bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# Check whether `docker` command requires sudo
if ! docker ps >/dev/null 2>/dev/null ; then
    USERNAME=$(whoami)

    ORCHEST_PATH=.
    # Check if orchest is in PWD
    if ! test -f "orchest"; then
        ORCHEST_PATH=$DIR
    fi

    echo "docker command not accesible for user '$USERNAME'."
    echo "Requiring 'sudo' for docker commands."
    SUDO_PREFIX="sudo"
fi

function update_orchest_ctl {
    # Update orchest-ctl to latest before performing update
    $SUDO_PREFIX docker pull orchest/orchest-ctl:latest
}

# Before running an update, update the orchest-ctl as the latest
# orchest-ctl should be used to update the application.
[[ "$1" == "update" ]] && [[ "$@" != *"--help"* ]] && update_orchest_ctl

HOST_CONFIG_DIR=$HOME/.config/orchest
HOST_USER_DIR=$DIR/userdir

# We detect the host OS to properly set the GID owner
# that is used for files in the userdir/
HOST_OS="linux"
if [[ "$OSTYPE" == "darwin"* ]]; then
    HOST_OS="darwin"
fi

# create config dir if it doesn't exist
mkdir -p "${HOST_CONFIG_DIR}"
$SUDO_PREFIX chown $USER "${HOST_CONFIG_DIR}"

$SUDO_PREFIX docker run \
    --rm \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v "${DIR}":/orchest-host \
    -v "${HOST_CONFIG_DIR}":/config \
    -e HOST_CONFIG_DIR="${HOST_CONFIG_DIR}" \
    -e HOST_REPO_DIR="${DIR}" \
    -e HOST_USER_DIR="${HOST_USER_DIR}" \
    -e HOST_OS="${HOST_OS}" \
    orchest/orchest-ctl:latest "$@"
